import {reqLoginUser, reqRegisterUser, reqGetUser, reqModifyUser} from '@/api/index'
import { getToken, setToken, removeToken } from '@/util/token';

const state = {
    // 数据初始值
    registerResult: false,
    token: getToken,
    username: '',
    userInfo: {},
}

const mutations = {
    // setRegisterResult(state, registerResult){
    //     state.registerResult = registerResult;
    // },
    setUserToken(state, token){
        state.token = token;
    },
    setUserInfo(state, userInfo){
        state.userInfo = userInfo;
    },
    setUserName(state, username){
        state.username = username;
    }
    ,
    clean(state){
        // 仓库中清空
        state.token = "",
        state.userInfo = {},
        // 本地清空
        removeToken;
    }
}

// 写到这里 可以通过 state. 识别到
const actions = {
    async registerUser({commit}, user){
        const result = await reqRegisterUser(user);
        if(result.code==200){
            commit('setRegisterResult',result.data)
        }else{
            return Promise.reject(new Error("fail"))
        }
    },
    async loginUser({commit}, user){
        const result = await reqLoginUser(user);
        if(result.code==200){
            // 在 vuex 缓存数据
            commit('setUserToken',result.data)
            commit('setUserName',user.username)
            console.log(user)
            const arr = result.data.split(' ')
            // console.log(arr[0])
            // console.log(arr[1])
            // 持久化存储 token
            setToken(arr[0])
            localStorage.setItem('userId',arr[1])
        }else{
            return Promise.reject(new Error("fail"))
        }
    },
    async getUserInfo({commit}, data){
        const result = await reqGetUser(data);
        if(result.code==200){
            commit('setUserInfo',result.data)
        }else{
            return Promise.reject(new Error("fail"))
        }
    },
    async modifyUserInfo({commit}, user){
        const result = await reqModifyUser(user);
        if(result.code==200){
            commit('setUserInfo',user)
        }else{
            return Promise.reject(new Error("fail"))
        }
    },
    userLogout({commit}){
        commit('setUserToken',null);
        localStorage.setItem('token',null);
    }
}

const getters = {
    getUserInfo: (state) => {
        return state.userInfo
    }
}

export default{
    state,
    mutations,
    actions,
    getters
}